<template>
  <div class="tab-content">
    <div class="tab-panel">
      <h2>哔哩哔哩热搜榜</h2>
      <div v-if="biliData.loading" class="loading">
        正在加载热搜...
      </div>
      <div v-else-if="biliData.error" class="error">
        {{ biliData.error }}
      </div>
      <div v-else class="bilibili-content">
        <div class="bilibili-list">
          <div class="bilibili-item" v-for="(item, index) in biliData.data" :key="index" @click="openLink(item.link)">
            <span class="rank">{{ index + 1 }}.</span>
            <span class="title">{{ item.title }}</span>
            <span class="hot" v-if="item.hot">热</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, toRefs, watch } from 'vue';
import { API_BASE_URL } from '../utils/WebConstants.ts';

const props = defineProps<{
  refreshKey?: number;
}>();

const { refreshKey } = toRefs(props);

const biliData = ref({
  loading: true,
  error: null as string | null,
  data: null as any,
});

// 获取B站热搜
const fetchBilibili = async () => {
  try {
    biliData.value.loading = true;
    const response = await fetch(`${API_BASE_URL}/bili`);
    const result = await response.json();

    // 检查响应是否成功
    if (result.code !== 200) {
      throw new Error(result.message || '获取数据失败');
    }

    // 使用JSON数据中的data字段
    biliData.value.data = result.data.map((item: any, index: number) => ({
      title: item.title,
      link: item.link,
      hot: index < 3, // 前3条标记为"热"
    }));
  } catch (err) {
    biliData.value.error = '网络错误，请稍后重试';
    console.error('获取B站热搜时出错:', err);
  } finally {
    biliData.value.loading = false;
  }
};

// 打开链接
const openLink = (link: string) => {
  if (link) {
    window.open(link, '_blank');
  }
};

// 监听刷新键变化
watch(refreshKey, () => {
  fetchBilibili();
});

onMounted(() => {
  fetchBilibili();
});
</script>

<style scoped>
.tab-panel h2 {
  text-align: center;
  margin-bottom: 20px;
  color: white;
}

.loading, .error {
  text-align: center;
  padding: 40px 20px;
  font-size: 1.2rem;
}

.loading {
  color: #ccc;
}

.error {
  color: #d32f2f;
}

.bilibili-list {
  background: #2d2d2d;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.bilibili-item {
  padding: 12px 0;
  border-bottom: 1px solid #444;
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}

.bilibili-item:hover {
  background-color: #3d3d3d;
}

.bilibili-item:last-child {
  border-bottom: none;
}

.rank {
  font-weight: bold;
  color: #42b983;
  min-width: 30px;
}

.title {
  flex: 1;
  color: #ddd;
}

.hot {
  background-color: #ff4d4d;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.8rem;
}

@media (max-width: 768px) {
  .bilibili-list {
    padding: 15px;
  }

  .bilibili-item {
    padding: 8px 0;
    gap: 6px;
  }
}
</style>